//^ -------------------- Base Extensions ------------------//
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

Date.prototype.format = function (format) {
    /*
     * eg:format="yyyy-MM-dd hh:mm:ss";
     */
    var o = {
        "M+": this.getMonth() + 1, // month
        "d+": this.getDate(), // day
        "h+": this.getHours(), // hour
        "m+": this.getMinutes(), // minute
        "s+": this.getSeconds(), // second
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter
        "S": this.getMilliseconds()
        // millisecond
    };

    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
            - RegExp.$1.length));
    }

    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};
//$ -------------------- Base Extensions ------------------//

//^ -------------------- Jquery Extensions ------------------//
(function ($) {
    jQuery.fn.extend({
        InputCurrency: function (opts) {
            opts = jQuery.extend({ }, opts || {});
            return this.each(function () {
                var _self = this;
                var _this = $(this);

                _this.css({ "text-align": "right", "ime-mode": "disabled" });

                _this.keypress(function (e) {
                    var _value = _self.value;
                    var _key = window.event ? e.keyCode : e.which;
                    var _keyValue = String.fromCharCode(_key);
                    if (_value.split(".").length - 1 == 1) {
                        if (!/^[\d]$/.test(_keyValue)) {
                            return false;
                        }
                    }
                    else {
                        if (!/^[\d\.]$/.test(_keyValue)) {
                            return false;
                        }
                    }
                });

            });
        }
    });
})(jQuery);
//$ -------------------- Jquery Extensions ------------------//


//^ -------------------- Utilities ------------------//
(function(_win) {
    var util = (function() {
        var util = function() {
            return util.fn.init();
        };

        util.fn = util.prototype = {
            init : function() {
                return this;
            },

            postData4DT: function (sSource, aoData, fnCallback) {
                $("[name^='s_']").each(function () {
                    var name = $(this).attr("name");
                    var val = $(this).val();
                    aoData.push({"name": name, "value": val});
                });

                $.ajax({
                    "dataType": 'json',
                    "type": "post",
                    "url": sSource,
                    "data": aoData,
                    "success": fnCallback
                });
            }

        };

        return util;
    })()();
    _win.util = util;
    return util;
})(window);
//$ -------------------- Utilities ------------------//

var dataTableSettings = {
    "bProcessing": true,
    "bAutoWith": false,
    "sScrollX": "100%",
    "bScrollCollapse": true,
    "sScrollY": 200,
//    "sDom": "Rlfrtip",
    "bFilter":false,
    "bSort": false,
    "oLanguage": {
        "sLengthMenu": "每页 _MENU_ 记录",
        "sZeroRecords": "没有发现任何记录",
        "sInfo": "显示 _START_ 到 _END_ 共 _TOTAL_ 记录",
        "sInfoEmpty": "显示 0 到 0 共 0 记录",
        "sInfoFiltered": "(filtered from _MAX_ total records)",
        "sSearch": "过滤",
        "sProcessing":"数据查询中...",
        "oPaginate": {
            "sNext": "下一页",
            "sPrevious": "上一页"
        }
    }
};

function checkRequired( o, n ) {
    if (o.val() == "" ||o.val().trim() == "" || o.val().length ==0 ) {
        o.addClass( "ui-state-error" );
        updateTips( "'" + n + "' 不能为空" );
        return false;
    } else {
        return true;
    }
}

function checkLength( o, n, min, max ) {
    if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "'" + n + "' 的长度应该在 " + min + " 和 " + max + " 之间" );
        return false;
    } else {
        return true;
    }
}

function checkRegexp( o, regexp, n ) {
    if ( !( regexp.test( o.val() ) ) ) {
        o.addClass( "ui-state-error" );
        updateTips( n );
        return false;
    } else {
        return true;
    }
}

function checkNumber( o, n ) {
    if ( isNaN(o.val())) {
        o.addClass( "ui-state-error" );
        updateTips( "'" + n + "' 应该是数字类型 ");
        return false;
    } else {
        return true;
    }
}

function checkNumberBetween( o, n, min, max ) {
    if ( o.val() > max || o.val() < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "'" + n + "' 的值应该在 " + min + " 和 " + max + " 之间" );
        return false;
    } else {
        return true;
    }
}

function updateTips( t ) {
    $( ".validateTips" ).text( t ).addClass( "ui-state-highlight" );
    setTimeout(function() {
        $( ".validateTips" ).removeClass( "ui-state-highlight", 1500 );
    }, 500 );
}


function deleteConfirm(_fun,_msg){
    if(_msg!=undefined && _msg!=null){
        $("#dialog-confirm-msg").text(_msg);
    }
    $("#dialog-confirm").dialog({
        resizable: false,
        height: 180,
        modal: true,
        buttons: {
            "确定": function () {
                _fun();
                $(this).dialog("close");
            },
            "取消": function () {
                $(this).dialog("close");
            }
        }
    });
}

function emailValidation(D) {
	var C = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
	if (C.test(D)) {
		return true
	}
	return false
}
$(function() {
	$("input:submit, input:reset, input:button").button()
});
$(function() {
	$.fn.auphonerule = function(B) {
		if (B.length >= 2) {
			phoneprefix = B.substr(0, 2);
			if (phoneprefix != "04") {
				$("#dialog:ui-dialog").dialog("destroy");
				$("#dialog-message")
						.html(
								"Not a valid mobile phone number.<br>Mobile Phone Number Rule: 04 + 8 digitals.");
				$("#dialog-message").dialog({
					modal : true,
					resizable : false,
					close : function(D, A) {
						$("#mobile").focus()
					},
					buttons : {
						Ok : function() {
							$(this).dialog("close")
						}
					}
				});
				return false
			}
		}
		if (B.length != 10) {
			$("#dialog:ui-dialog").dialog("destroy");
			$("#dialog-message")
					.html(
							"Not a valid mobile phone number.<br>Mobile Phone Number Rule: 04 + 8 digitals.");
			$("#dialog-message").dialog({
				modal : true,
				resizable : false,
				close : function(D, A) {
					$("#mobile").focus()
				},
				buttons : {
					Ok : function() {
						$(this).dialog("close")
					}
				}
			});
			return false
		}
		return true
	};
	$.fn.numeral = function() {
		$(this).css("ime-mode", "disabled");
		this.bind("keypress", function(D) {
			var C = (D.keyCode ? D.keyCode : D.which);
			if (!$.browser.msie && (D.keyCode == 8)) {
				return
			}
			return C >= 48 && C <= 57
		});
		this.bind("blur", function() {
			if (this.value.lastIndexOf(".") == (this.value.length - 1)) {
				this.value = this.value.substr(0, this.value.length - 1)
			} else {
				if (isNaN(this.value)) {
					this.value = ""
				}
			}
		});
		this.bind("paste", function() {
			var B = clipboardData.getData("text");
			if (!/\D/.test(B)) {
			}
			this.value = B;
			return false
		});
		this.bind("dragenter", function() {
			return false
		});
		this.bind("keyup", function() {
		})
	}
});
function areDuplicateLocations(E, D, F) {
	if (D != "" && E == D) {
		return true
	}
	if (F != "" && E == F) {
		return true
	}
	if (D != "" && F != "") {
		if (E == D || D == F || E == F) {
			return true
		}
	}
	return false
}
function parseDT(B) {
	arr = B.split("/");
	return new Date(arr[2], arr[1] - 1, arr[0]).getTime()
}
function parseD(B) {
	arr = B.split("/");
	return new Date(arr[2], arr[1] - 1, arr[0])
}
function areDuplicatePreferedDates(E, D, F) {
	ct = new Date();
	current = new Date(ct.getFullYear(), ct.getMonth(), ct.getDate()).getTime();
	d1 = E.substring(0, 10);
	d2 = D.substring(0, 10);
	d3 = F.substring(0, 10);
	d1_t = parseDT(d1);
	d2_t = parseDT(d2);
	d3_t = parseDT(d3);
	d1_d = parseD(d1);
	d2_d = parseD(d2);
	d3_d = parseD(d3);
	if (E != "") {
		if (d1_d.getDay() == 0 || d1_d.getDay() == 1) {
			return true
		}
	}
	if (D != "") {
		if (d2_d.getDay() == 0 || d2_d.getDay() == 1) {
			return true
		}
	}
	if (F != "") {
		if (d3_d.getDay() == 0 || d3_d.getDay() == 1) {
			return true
		}
	}
	if (D == "" && F == "") {
		return false
	}
	if (d1_t < current || d2_t < current || d3_t < current) {
		return true
	}
	if (d2 != "" && d3 != "") {
		if (d1 == d2 || d1 == d3 || d2 == d3) {
			return true
		}
	}
	if (d2 != "" && d1 == d2) {
		return true
	}
	if (d3 != "" && d1 == d3) {
		return true
	}
	return false
};

(function( $ ) {
	$.widget( "ui.combobox", {
		_create: function() {
			var input,
				self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "",
				wrapper = this.wrapper = $( "<span>" )
					.addClass( "ui-combobox" )
					.insertAfter( select );

			input = $( "<input>" )
				.appendTo( wrapper )
				.val( value )
				.addClass( "ui-state-default ui-combobox-input" )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						ui.item.option.selected = true;
						self._trigger( "selected", event, {
							item: ui.item.option
						});
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								// remove invalid value, as it didn't match
								// anything
								$( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};

			$( "<a>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Show All Items" )
				.appendTo( wrapper )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-combobox-toggle" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					// work around a bug (likely same cause as #5265)
					$( this ).blur();

					// pass empty string as value to search for, displaying all
					// results
					input.autocomplete( "search", "" );
					input.focus();
				});
		},

		destroy: function() {
			this.wrapper.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}
	});
})( jQuery );

(function($) {
	 jQuery.fn.extend({
	  InputCurrency: function(opts) {
	   opts = jQuery.extend({ }, opts || {});
	  return this.each(function() {
	   var _self = this;
	   var _this = $(this);

	   _this.css({ "text-align": "right", "ime-mode": "disabled" });

	   _this.keypress(function(e) {
	    var _value = _self.value;
	    var _key = window.event ? e.keyCode : e.which;
	    var _keyValue = String.fromCharCode(_key);
	    if (_value.split(".").length - 1 == 1) {
	     if (!/^[\d]$/.test(_keyValue)) {
	      return false;
	     }
	    }
	    else {
	     if (!/^[\d\.]$/.test(_keyValue)) {
	      return false;
	     }
	    }
	   });

	  });
	 }
	});
	})(jQuery);

//背景图自适应
(function($) {
    $.fn.fullBg = function(){
        var bgImg = $(this);
        bgImg.addClass('fullBg');
        function resizeImg() {
            var imgwidth = bgImg.width();
            var imgheight = bgImg.height();
            var winwidth = $(window).width();
            var winheight = $(window).height();
            var widthratio = winwidth/imgwidth;
            var heightratio = winheight/imgheight;
            var widthdiff = heightratio*imgwidth;
            var heightdiff = widthratio*imgheight;
            if(heightdiff>winheight) {
                bgImg.css({
                    width: winwidth+'px',
                    height: heightdiff+'px'
                });
            } else {
                bgImg.css({
                    width: widthdiff+'px',
                    height: winheight+'px'
                });
            }
        }
        resizeImg();
        $(window).resize(function() {
            resizeImg();
        });
    };

})(jQuery)

$(function(){
    $(".menu_1st").click(
        function () {
            $(this).siblings(".sublist").show();
            $(this).parent("li").siblings().children().find(".sublist").hide();
            $(this).addClass("menu_1st_hover");
            $(this).parent().siblings().children().removeClass("menu_1st_hover");
            $(this).parent().siblings().children(".sublist").hide();
        }
    );
});


/*=============================window opener ^===============================*/

var winOpened;
function closeWin(){
    if(winOpened){
        winOpened.close();
    }
}
function openWin(url){
    closeWin();
    winOpened = openWindow(url,"",1024,768);
}

function openWin2(url){
    closeWin();
    winOpened = openWindow(url,"",600,400);
}

function openWin3(url){
    closeWin();
    winOpened = openWindow(url,"",1024,768);
}

function openWindow(url, name, iWidth, iHeight) {
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
    return window.open(url, name, 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ', depended=yes,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no');
}

function linkTo(_link,_win){
    var _home =  window.frames["homePage"];
    if(_win){
        _win.location = _link;
    }else if(_home){
        _home.location.href = _link;
    }else{
        window.location.href = _link;
    }
}

function menuLink(_link,_obj){
    $(_obj).parent().addClass("selected").siblings().removeClass("selected");

    linkTo(_link);
}
/*=============================window opener &===============================*/

/*=============================Object check ^===============================*/
function isArray(obj) {
    return (typeof obj == 'object') && obj.constructor == Array;
}
function isString(str) {
    return (typeof str == 'string') && str.constructor == String;
}
function isNumber(obj) {
    return (typeof obj == 'number') && obj.constructor == Number;
}
function isDate(obj) {
    return (typeof obj == 'object') && obj.constructor == Date;
}
function isFunction(obj) {
    return (typeof obj == 'function') && obj.constructor == Function;
}
function isObject(obj) {
    return (typeof obj == 'object') && obj.constructor == Object;
}
/*=============================Object check &===============================*/

/*=============================link tag ^===============================*/
function tagLink(_funStr,_desc){
   return "<a href=\"javascript:void(0)\" onclick=\""+_funStr+"\">"+_desc+"</a>";
}

function tagLinkView(_funStr){
   return tagLink(_funStr,"详细");
}

function tagLinkEdit(_funStr){
   return tagLink(_funStr,"编辑");
}

function tagLinkDel(_funStr){
    return tagLink(_funStr,"删除");
}


/*=============================ui helpers ^===============================*/
var uiHelper = {
    __version:1.2,
    parseJSON:function(response){    	
		if(typeof(response)=="object") return response;    	
    	
        if(response !=null && response.length>0){
            response = eval("("+response+")");
            if(typeof response.status == 'undefined' || (response.status == "FAILED" && response.code == "U00")){
                return null;
            }
            return response;
        }else{
            return null;
        }
    },

    checkLicense: function(){
       $.ajax({
           url: "${ctx}/license/check",
           /* data: {"id": param}, */
           success: function (data) {
               if(data == 'Y'){
                $.prompt("许可证已经到期，请重新输入!");
               }
           }
       });
    },

    checkLoginPage:function(){
        if(self != top && window.parent.uiHelper){
            window.parent.location.reload();
        }
    },

    mask:{
        _e : null,
        init:function(){
            this._e = $("<div class='loading'>系统正在处理</div>").appendTo("<body/>");
            this._e.dialog({
                draggable:false,
                autoOpen: false,
                resizable: false,
                height: 70,
                width:180,
                modal: true,
                closeOnEscape:false,
                open:function(event,ui){uiHelper.mask._e.parent().find(".ui-dialog-titlebar").hide();}
            });
            return this;
        },

        open:function(){
            this._e.dialog("open");
        },

        close:function(){
            this._e.dialog("close");
        }

    }
}

/*=============================progress bar ^===============================*/
var progressMgr = {
    __version:1.6,
    total:0,
    cache:[],
    container:null,
    _selfCnt:false,
    createProgressbar:function(container,_key,intervalFun){
        var pb = {
            _t:"S",
            _max:100,
            _frequency:2000,
            total:0,
            fn:null,
            ps:null,
            getPN:function(){
                return this.ps.attr("pn");
            },
            cleanMsg:function(){
                this.ps.find(".message_area").empty();
                return this;
            },
            addMsg:function(msg){
                this.ps.find(".message_area").append("<p>" + msg + "</p>");
                return this;
            },
            setPN:function(pn) {
                this.ps.attr("pn",pn);
                this.ps.find(".progressbar").progressbar("option", "value", pn).children('span.caption').html("完成" + pn + '%');
                this.ps.find(".progressbar").show();
                return this;
            },
            intervalID:null,
            stop:function(){
                clearInterval(this.intervalID);
                return this;
            },
            create:function(_fn){
                this.fn = _fn;
                this.ps = $("<div class=\"progress_section\" ><div class=\"progressbar\"><span class=\"caption\">正在处理...请稍等!</span></div><div class=\"message_area\"></div></div>").clone();
                this.ps.attr("fn",_fn);
                return this;
            },
            init:function(_c){
                this.ps.attr("pn",1);
                _c.append(this.ps);
                this.ps.find(".progressbar").progressbar({
                    value: this.ps.attr("pn"),
                    max: this._max
                });
                this.setPN(this.ps.attr("pn"));
                return this;
            },
            remove:function(){
                if(this._t == 'N'){
                    this.ps.parent().parent().remove();
                }else{
                    this.ps.remove();
                }
                progressMgr.cache[this.fn] = null;
            },
            status:function(_success){
                if(this._t == 'N'){
                    var _status = this.ps.parent().parent().find(".pg_step_status");
                    if(_status.length>0){
                        _status.remove();
                    }

                    if(_success){
                        this.ps.parent().parent().append("<div class='pg_step_status success'></div>");
                    }else{
                        this.ps.parent().parent().append("<div class='pg_step_status failed'></div>");
                    }
                }
                return this;

            },
            forward:function(_completed){
                var progress = parseInt(this.getPN());
                if (_completed) {
                    progress = this._max;
                } else {
                    progress ++;
                    if(progress >= this._max){
                        progress = this._max - 1;
                    }
                }
                this.setPN(progress);
                return this;
            },

            forward2:function(_count,_total){
                if(typeof _total != "undefined" && !isNaN(_total)){
                    this.total = _total;
                }

                if(isNaN(_count) || this.total==0)return this;

                if(_count >= this.total){
                    _count = this.total;
                }

                this.setPN(Math.floor((_count/this.total)*100));
                return this;
            },

            estimate:function(_duration){
                this._frequency = Math.floor(_duration/100);
                return this;
            }

        };

        pb.create(_key).init(container);


        if(intervalFun){
            pb.intervalID = setInterval(intervalFun,pb._frequency);
        }

        this.cache[_key] = pb;
        return pb;
    },

    getProgressbar:function(_key){
        return this.cache[_key];
    },

    delProgressbar:function(_key){
        var pg = this.getProgressbar(_key);
        if(pg){
            pg.stop();
            pg.remove();
        }
    },

    stopListener:function(_key){
        var pb = this.getProgressbar(_key);
        if(pb){
            pb.stop();
        }
    },

    stopAll:function(){
        for(var i in this.cache){
            this.stopListener(i);
        }
    },

    setContainer : function(_container){
        if(_container){
            this.container = $(_container);
        }else{
            this.container = $("<div class='progress_container'></div>").appendTo("<body/>");
            this.container.dialog({
                title:"系统处理中...",
                draggable:false,
                autoOpen: false,
                resizable: false,
                height: 200,
                width: 650,
                modal: true,
                closeOnEscape:false,
                close:function(event,ui){$(event.target).empty();}
            });
            this._selfCnt = true;
        }
    },

    getContainer : function(){
        if(this.container==null){
            this.setContainer();
        }
        return this.container;
    },

    showContainer: function(){
        if(this.container!=null){
            if(this._selfCnt){
                this.container.dialog("open");
            }else{
                this.container.show();
            }
        }
    },

    setContainerTitle: function(_title){
        if(this.container!=null){
            if(this._selfCnt){
                this.container.dialog("option", "title", _title);
            }
        }
    },

    createProgress: function (_key, intervalFun, _container) {
        if (typeof _container == undefined || _container == null) {
            return this.createProgressbar(this.getContainer(), _key, intervalFun);
        } else {
            return this.createProgressbar(_container, _key, intervalFun);
        }
    },

    createStatusbar : function(_title,_key,intervalFun,_parent){
        var _s = $("<div class=\"pg_step\"><div class=\"pg_step_title\">"+(_title?_title:'')+"</div></div>");
        var _c = $("<div class=\"pg_bar\"></div>");
        if(typeof _parent == undefined || _parent == null){
            this.getContainer().append(_s.append(_c));
            this.showContainer();
        }else{
            _parent.append(_s.append(_c));
        }

        var pb = this.createProgress(_key,intervalFun,_c);
        pb._t = "N";
        return pb;

    }


};


/*====================================================================================*/
